<?php
/**
 *@author Connor <caokang@foxmail.com>
 *@todo
 *@link www.zeevin.com
 */
class Pm extends CActiveRecord{

	const PAGE_SIZE=10;

	const PM_READ_STATUS_NO = 0;//未读
	const PM_READ_STATUS_YES =1;//已读

	const PM_STATUS_OK=0;
	const PM_STATUS_SPAMS=1;//垃圾信息
	
	const PM_DEL_NORMAL=0;//正常
	const PM_DEL_BY_FROM=1;//被发送方删除
	const PM_DEL_BY_TO=2;//被接收方删除
	const PM_DEL_BY_BOTH=3;//被双方删除

	public static function model($className=__CLASS__){
		return parent::model($className);
	}

	public function tableName(){
		return 'pm_messages';
	}	



	protected function beforeSave()
	{
		if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
				$this->ctime=date('Y-m-d H:i:s');
				$this->from_uid=Yii::app()->user->id;
			}
			return true;
		}
		else
			return false;
	}

	public function rules(){
		return array(
			array('subject,content,to_uid','required'),
			array('subject', 'length', 'max'=>255,'message'=>'标题太长，不能超过255个字符'),
			);
	}

	//分页查询收发件箱
	public static function getList($param=array()){
		// print_r($param);
		$condition = '';
		$criteria=new CDbCriteria();
		if(isset($param['fid'])){
			$condition .= $condition?" AND from_uid=:fid ":'  from_uid=:fid ';
			$params[':fid']=$param['fid'];
		}
		if(isset($param['tid'])){
			$condition .= $condition?" AND to_uid=:tid ":"  to_uid=:tid ";
			$params[':tid']=$param['tid'];
		}
		if(isset($param['isread'])){
			$condition .= $condition?" AND is_read=:isread ":"  is_read=:isread ";
			$params[':isread']=$param['isread'];
		}
		if(isset($param['s'])){
			$condition .= $condition?" AND status=:s ":"  status=:s ";
			$params[':s']=$param['s'];
		}

		if(isset($param['del_status'])){
			$condition .= $condition?" AND del_status=:del_status ":" del_status=:del_status ";
			$params[':del_status'] = $param['del_status'];
		}
		if(isset($param['del_status_sec'])){
			$condition .= $condition?" AND del_status_sec=:del_status_sec ":" del_status_sec=:del_status_sec ";
			$params[':del_status_sec'] = $param['del_status_sec'];
		}
		

		$criteria->condition = $condition;
		$criteria->params = $params;
		$criteria->order = 'id DESC';
    	$count=Pm::model()->count($criteria);
    	$pages=new CPagination($count);

    	// results per page
   	 	$pages->pageSize=self::PAGE_SIZE;
    	$pages->applyLimit($criteria);
    	$rs['total_num'] = $count;
    	$rs['rows'] = Pm::model()->findAll($criteria);
    	$rs['pages'] = $pages;
    	return $rs;
	}
}